package com.atzly.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.Message;
import com.atzly.community.entity.Page;
import com.atzly.community.entity.User;
import com.atzly.community.service.MessageService;
import com.atzly.community.service.UserService;
import com.atzly.community.utils.CommunityUtils;
import com.atzly.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 私信
 *
 * @author zlysimida
 * @date 2021/8/29 - 19:16
 */
@Controller
@RequestMapping("/message")
public class MessageController implements CommentConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    // 获取当前用户下所有私信通知
    @GetMapping("/list")
    public String showConservations(Model model, Page page) {
        User user = hostHolder.getUserFromThread();
        page.setLimit(5);
        page.setPath("/message/list");
        page.setTotal(messageService.getMessagePageCounts(user.getId()));

        List<Message> conversationList = messageService.getAllMessagePage(
                user.getId(), page.getOffset(), page.getLimit());

        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> conversation = new HashMap<>();
                conversation.put("conversation", message);
                conversation.put("letterCount", messageService.getLetterCount(message.getConversationId()));
                conversation.put("unReadCount", messageService.getNoReadLetterCount(user.getId(), message.getConversationId()));
                // 显示对方用户
                int target = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                conversation.put("target", userService.selectById(target));
                conversations.add(conversation);
            }
        }
        model.addAttribute("conversations", conversations);

        // 查询用户所有未读数量
        int noReadLetterCount = messageService.getNoReadLetterCount(user.getId(), null);
        model.addAttribute("letterNoReadCounts", noReadLetterCount);

        // 未读系统通知数量
        int noticNoReadCount = messageService.selectSystemNoReadNotify(user.getId(), null);
        model.addAttribute("noticeNoReadCount", noticNoReadCount);

        return "/site/letter";
    }

    @GetMapping("/detail/{conversationId}")
    public String showDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
        page.setLimit(5);
        page.setPath("/message/detail/" + conversationId);
        page.setTotal(messageService.getLetterCount(conversationId));

        // 获取全部私信
        List<Message> letterList = messageService.getLetter(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> letter = new HashMap<>();
                letter.put("letter", message);
                letter.put("fromUser", userService.selectById(message.getFromId()));
                letters.add(letter);
            }
        }
        model.addAttribute("letters", letters);

        // 添加私信的目标对象
        model.addAttribute("target", getTargetUser(conversationId));


        // 设置已读
        List<Integer> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.updateMessageStatus(ids);
        }
        return "/site/letter-detail";
    }

    @PostMapping("/send")
    @ResponseBody
    public String sendLetter(String toName, String content) {
        User target = userService.selectByName(toName);
        if (target == null) {
            return CommunityUtils.JsontoString(1, "发送的目标用户不存在");
        }
        Message message = new Message();
        message.setContent(content);
        message.setCreateTime(new Date());
        int fromId = hostHolder.getUserFromThread().getId();
        int toId = target.getId();
        message.setFromId(fromId);
        message.setStatus(CommentConstant.LETTER_STATUS_UNREAD);
        message.setToId(toId);
        if (toId > fromId) {
            message.setConversationId(fromId + "_" + toId);
        } else {
            message.setConversationId(toId + "_" + fromId);
        }
        messageService.insertMessage(message);
        return CommunityUtils.JsontoString(0, "发送成功!");
    }

    // 通知列表功能
    @GetMapping("/notify/list")
    public String notifyList(Model model) {
        User user = hostHolder.getUserFromThread();

        // 查询评论类通知
        Message message = messageService.selectSystemLatestNotify(user.getId(), TOPIC_COMMENT_KEY);
        Map<String, Object> messageVo = new HashMap<>();
        messageVo.put("message", message);
        if (message != null) {
            Map<String, Object> content = JSONObject.parseObject(message.getContent(), HashMap.class);
            messageVo.put("user", userService.selectById((Integer) content.get("userId")));
            messageVo.put("entityType", content.get("entityType"));
            messageVo.put("entityId", content.get("entityId"));
            messageVo.put("postId", content.get("postId"));
            int count = messageService.selectSystemNotifyCount(user.getId(), TOPIC_COMMENT_KEY);
            messageVo.put("count", count);
            int unRead = messageService.selectSystemNoReadNotify(user.getId(), TOPIC_COMMENT_KEY);
            messageVo.put("unRead", unRead);
        }
        model.addAttribute("commentNotice", messageVo);

        // 查询点赞类通知
        message = messageService.selectSystemLatestNotify(user.getId(), TOPIC_LIKE_KEY);
        messageVo = new HashMap<>();
        messageVo.put("message", message);
        if (message != null) {

            Map<String, Object> content = JSONObject.parseObject(message.getContent(), HashMap.class);
            messageVo.put("user", userService.selectById((Integer) content.get("userId")));
            messageVo.put("entityType", content.get("entityType"));
            messageVo.put("entityId", content.get("entityId"));
            messageVo.put("postId", content.get("postId"));
            int count = messageService.selectSystemNotifyCount(user.getId(), TOPIC_LIKE_KEY);
            messageVo.put("count", count);
            int unRead = messageService.selectSystemNoReadNotify(user.getId(), TOPIC_LIKE_KEY);
            messageVo.put("unRead", unRead);
        }
        model.addAttribute("likeNotice", messageVo);

        // 查询关注类通知
        message = messageService.selectSystemLatestNotify(user.getId(), TOPIC_FOLLOW_KEY);
        messageVo = new HashMap<>();
        messageVo.put("message", message);
        if (message != null) {
            Map<String, Object> content = JSONObject.parseObject(message.getContent(), HashMap.class);
            messageVo.put("user", userService.selectById((Integer) content.get("userId")));
            messageVo.put("entityType", content.get("entityType"));
            messageVo.put("entityId", content.get("entityId"));
            //messageVo.put("postId",content.get("postId"));
            int count = messageService.selectSystemNotifyCount(user.getId(), TOPIC_FOLLOW_KEY);
            messageVo.put("count", count);
            int unRead = messageService.selectSystemNoReadNotify(user.getId(), TOPIC_FOLLOW_KEY);
            messageVo.put("unRead", unRead);
        }
        model.addAttribute("followNotice", messageVo);

        // 查询所有未读关注数量
        int noticNoReadCount = messageService.selectSystemNoReadNotify(user.getId(), null);
        model.addAttribute("noticeNoReadCount", noticNoReadCount);
        int letterNoReadCount = messageService.getNoReadLetterCount(user.getId(), null);
        model.addAttribute("letterNoReadCount", letterNoReadCount);
        return "/site/notice";
    }

    @GetMapping("/notify/details/{topic}")
    public String notifyDetails(@PathVariable("topic") String topic, Model model, Page page) {
        User user = hostHolder.getUserFromThread();

        page.setLimit(5);
        page.setPath("/message/notify/details/" + topic);
        page.setTotal(messageService.selectSystemNotifyCount(user.getId(), topic));

        List<Message> messageList = messageService.selectDetailsNotifyAndPage(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeVo = new ArrayList<>();
        if (messageList != null) {
            for (Message message : messageList) {
                Map<String, Object> notice = new HashMap<>();
                notice.put("notice", message);
                Map<String, Object> content = JSONObject.parseObject(message.getContent(), HashMap.class);
                notice.put("user", userService.selectById((Integer) content.get("userId")));
                notice.put("entityType", content.get("entityType"));
                notice.put("entityId", content.get("entityId"));
                notice.put("postId", content.get("postId"));
                // 获取通知作者
                notice.put("fromUser", userService.selectById(message.getFromId()));
                noticeVo.add(notice);
            }
        }
        model.addAttribute("notices", noticeVo);

        // 未读消息设置已读
        List<Integer> ids = getLetterIds(messageList);
        if (!ids.isEmpty()) {
            messageService.updateMessageStatus(ids);
        }

        return "/site/notice-detail";
    }


    // 根据conversationId获得目标用户
    private User getTargetUser(String conversationId) {
        String[] s = conversationId.split("_");
        int s1 = Integer.parseInt(s[0]);
        int s2 = Integer.parseInt(s[1]);
        if (s1 == hostHolder.getUserFromThread().getId()) {
            return userService.selectById(s2);
        } else {
            return userService.selectById(s1);
        }
    }

    // 查找当前用户未读的消息的ids
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getUserFromThread().getId() == message.getToId() && message.getStatus() == CommentConstant.LETTER_STATUS_UNREAD) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
}
